using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.Products.Commands;

/// <summary>
/// 产品强制 NG 命令。
/// </summary>
/// <param name="Id">产品状态 Id</param>
public sealed record UnfitProductCommand(long Id) : IRequest<IResult<bool>>;

internal sealed class UnfitProductCommandHandler(IRepository<ProdCurrentState> repo) : IRequestHandler<UnfitProductCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UnfitProductCommand request, CancellationToken cancellationToken)
    {
        var currentState = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (currentState == null)
        {
            return Result.Failure("未找到要更新的产品");
        }

        if (currentState.Status is not PassEnum.OK and not PassEnum.ForceOK)
        {
            return Result.Failure("产品只有在 OK 状态下才能强制 NG");
        }

        currentState.Status = PassEnum.ForceNG;
        currentState.UnfitCount += 1;
        var ok = await repo.UpdateAsync(currentState, m => new
        {
            m.Status,
            m.UnfitCount,
        }, cancellationToken);
        return Result.From(ok);
    }
}
